package com.zsr.dao.impl;

import com.zsr.dao.BookDao;
import com.zsr.pojo.Book;

import java.util.List;

public class BookDaoImpl extends BaseDao implements BookDao {

    @Override
    public int addBook(Book book) {
        String sql = "insert into t_book(`name`,`author`,`price`,`sales`,`stock`,`img_path`) values(?,?,?,?,?,?); ";
        return update(sql, book.getName(), book.getAuthor(), book.getPrice(), book.getSales(), book.getStock(), book.getImgPath());
    }

    @Override
    public int deleteBookById(Integer id) {
         String sql ="delete from t_book where id= ? ";
        return update(sql,id);
    }

    @Override
    public int updateBook(Book book)
    {
        String sql ="update t_book set `name`= ?,`author` = ? ,`price` = ?,`sales` = ?,`stock` = ?,`img_path` = ? where id= ? ";
        return update(sql,book.getName(),book.getAuthor(),book.getPrice(),book.getSales(),book.getStock(),
                book.getImgPath(),book.getId());
    }

    @Override
    public Book queryBookById(Integer id) {
        String sql ="select `id`,`name`,`author`,`price`,`sales`,`stock`,`img_path` imgPath from t_book where id= ? ";
        return queryForOne(Book.class,sql,id);
    }

    @Override
    public List<Book> queryBooks() {
        String sql ="select `id`,`name`,`author`,`price`,`sales`,`stock`,`img_path` imgPath from t_book";


        return queryForList(Book.class,sql);
    }

    /***
     * 查询总记录数
     * @return 总记录数
     */
    @Override
    public Integer queryForPageTotalCount() {
        String sql = "select count(*) from t_book";
        /**
         * Number类是java.lang包下的一个抽象类，提供了将包装类型拆箱成基本类型的方法，
         * 数字类型（整数和浮点数）都继承了该抽象类，并且是final声明不可继承改变
         */
        Number count =(Number)queryForSingleValue(sql);
        return count.intValue();
    }

    /**
     * 查询每页数据列表
     * @param begin 开始数据索引
     * @param pageSize 每页数量
     * @return
     */
    @Override
    public List<Book> queryForPageItems(int begin, int pageSize) {
        String sql ="select `id`,`name`,`author`,`price`,`sales`,`stock`,`img_path` imgPath from t_book limit ? ,? ";
        return queryForList(Book.class,sql,begin,pageSize);
    }

    /**
     * 根据价格区间查询记录数
     * @param min 最小价格
     * @param max 最大价格
     * @return
     */
    @Override
    public Integer queryForPageTotalCount(int min, int max) {
        String sql ="select count(*) from t_book where price between ? and ?";
        Number count =(Number)queryForSingleValue(sql,min,max);
        return count.intValue();
    }

    /**
     * 根据价格查询每页记录数
     * @param begin
     * @param pageSize
     * @param min
     * @param max
     * @return
     */
    @Override
    public List<Book> queryForPageItems(int begin, int pageSize, int min, int max) {
        String sql ="select `id`,`name`,`author`,`price`,`sales`,`stock`,`img_path` imgPath from t_book where price " +
                "between ? and ? limit ?,?";
        return queryForList(Book.class,sql,min,max,begin,pageSize);
    }
}
